﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;

namespace LinkDownloader
{
    internal static class GlobalSettings
    {

        private volatile static Settings settings = null;
        public static Settings Settings
        {
            get { return settings; }
        }

        /// <summary>
        /// The path of the settings file to load.
        /// </summary>
        public const string SettingsFile = "settings.xml";

        /// <summary>
        /// Load the global settings
        /// </summary>
        /// <returns>Whether the settings were loaded successfully.</returns>
        public static bool LoadSettings()
        {

            try
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(LinkDownloader.Settings));
                TextReader textReader = new StreamReader(SettingsFile);
                settings = (Settings)deserializer.Deserialize(textReader);
                textReader.Close();
                return true;
            }
            catch
            {
                settings = new Settings();
                return false;
            }

        }

        /// <summary>
        /// Save the global settings
        /// </summary>
        /// <returns>Whether the settings were saved successfully.</returns>
        public static bool SaveSettings()
        {

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(LinkDownloader.Settings));
                TextWriter textWriter = new StreamWriter(SettingsFile);
                serializer.Serialize(textWriter, settings);
                textWriter.Close();
                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// Initializes the Settings
        /// </summary>
        public static void InitializeSettings()
        {
            // add any initialization that's required.
        }

        /// <summary>
        /// Encrypt given string to HEX using SHA1 algorithm.
        /// </summary>
        /// <param name="text">The text to be encrypted.</param>
        /// <returns>The encrypted string.</returns>
        public static string EncryptBySHA1(string text)
        {
            // Gets the SHA1 hash for text
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(Encoding.Default.GetBytes(text));
            // Transforms as hexa
            string hexaHash = string.Empty;
            foreach (byte b in hash)
            {
                hexaHash += String.Format("{0:x2}", b);
            }
            // Returns SHA1 hexa hash
            return hexaHash;
        }

    }
}
